<template>
  <div class="training-records section-container">
    <div class="page-header">
      <h2 class="page-title">培训记录管理</h2>
      <p class="page-subtitle">管理和跟踪员工的培训参与情况、考核成绩及反馈</p>
    </div>
    
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="培训ID">
          <el-input v-model="searchForm.trainingId" placeholder="输入培训ID" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="员工ID">
          <el-input v-model="searchForm.employeeId" placeholder="输入员工ID" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTrainingRecords" class="search-btn">查询</el-button>
          <el-button @click="resetSearch" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="openAddDialog" class="action-btn">
        <i class="el-icon-plus"></i> 添加培训记录
      </el-button>
      <el-button type="success" @click="openBatchAddDialog" class="action-btn">
        <i class="el-icon-upload"></i> 批量添加
      </el-button>
    </div>
    
    <!-- 数据表格 -->
    <el-card class="data-card">
      <el-table :data="trainingRecords" border stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
        <el-table-column prop="trainingId" label="培训ID" width="100"></el-table-column>
        <el-table-column prop="employeeId" label="员工ID" width="100"></el-table-column>
        <el-table-column prop="attendance" label="出勤状态" width="120">
          <template #default="scope">
            <el-tag :type="getAttendanceTagType(scope.row.attendance)">
              {{ formatAttendance(scope.row.attendance) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="考核得分" width="100"></el-table-column>
        <el-table-column prop="feedback" label="评价反馈" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加培训记录' : '编辑培训记录'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="培训ID" prop="trainingId">
          <el-input v-model.number="form.trainingId" placeholder="请输入培训ID"></el-input>
        </el-form-item>
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model.number="form.employeeId" placeholder="请输入员工ID"></el-input>
        </el-form-item>
        <el-form-item label="出勤状态" prop="attendance">
          <el-select v-model="form.attendance" placeholder="请选择出勤状态">
            <el-option label="未签到" :value="0"></el-option>
            <el-option label="已签到" :value="1"></el-option>
            <el-option label="迟到" :value="2"></el-option>
            <el-option label="早退" :value="3"></el-option>
            <el-option label="缺席" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核得分" prop="score">
          <el-input-number v-model="form.score" :min="0" :max="100" :precision="2" placeholder="请输入考核得分"></el-input-number>
        </el-form-item>
        <el-form-item label="评价反馈" prop="feedback">
          <el-input type="textarea" v-model="form.feedback" placeholder="请输入评价反馈"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 批量添加对话框 -->
    <el-dialog
      title="批量添加培训记录"
      v-model="batchDialogVisible"
      width="500px"
    >
      <el-form :model="batchForm" ref="batchFormRef" label-width="100px">
        <el-form-item label="培训ID" prop="trainingId">
          <el-input v-model.number="batchForm.trainingId" placeholder="请输入培训ID"></el-input>
        </el-form-item>
        <el-form-item label="员工ID列表" prop="employeeIds">
          <el-input type="textarea" v-model="batchForm.employeeIdsString" placeholder="请输入员工ID，多个ID用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="出勤状态" prop="attendance">
          <el-select v-model="batchForm.attendance" placeholder="请选择出勤状态">
            <el-option label="未签到" :value="0"></el-option>
            <el-option label="已签到" :value="1"></el-option>
            <el-option label="迟到" :value="2"></el-option>
            <el-option label="早退" :value="3"></el-option>
            <el-option label="缺席" :value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBatchForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import request from '../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TrainingRecords',
  setup() {
    // 数据列表
    const trainingRecords = ref([])
    const loading = ref(false)
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      trainingId: '',
      employeeId: ''
    })
    
    // 表单数据
    const formRef = ref(null)
    const form = reactive({
      id: null,
      trainingId: '',
      employeeId: '',
      attendance: 0,
      score: null,
      feedback: ''
    })
    
    // 批量添加表单
    const batchFormRef = ref(null)
    const batchForm = reactive({
      trainingId: '',
      employeeIdsString: '',
      attendance: 0
    })
    
    // 对话框控制
    const dialogVisible = ref(false)
    const batchDialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    
    // 表单验证规则
    const rules = {
      trainingId: [
        { required: true, message: '请输入培训ID', trigger: 'blur' },
        { type: 'number', message: '培训ID必须为数字', trigger: 'blur' }
      ],
      employeeId: [
        { required: true, message: '请输入员工ID', trigger: 'blur' },
        { type: 'number', message: '员工ID必须为数字', trigger: 'blur' }
      ],
      attendance: [
        { required: true, message: '请选择出勤状态', trigger: 'change' }
      ]
    }
    
    // 加载培训记录列表
    const loadTrainingRecords = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        if (searchForm.trainingId) {
          params.trainingId = searchForm.trainingId
        }
        
        if (searchForm.employeeId) {
          params.employeeId = searchForm.employeeId
        }
        
        console.log('Sending request to fetch training records with params:', params)
        const res = await request.get('/api/training/records', { params })
        console.log('Training records response:', res)
        
        // 后端返回成功状态码为200
        if (res.code === 200) {
          // 检查数据格式是否正确
          if (res.data && Array.isArray(res.data.records)) {
            console.log('Records received:', res.data.records.length)
            trainingRecords.value = res.data.records
            total.value = res.data.total || 0
          } else if (Array.isArray(res.data)) {
            // 如果后端直接返回数组而非分页对象
            console.log('Array data received:', res.data.length)
            trainingRecords.value = res.data
            total.value = res.data.length
          } else {
            console.error('Unexpected data format:', res.data)
            trainingRecords.value = []
            total.value = 0
            ElMessage.warning('数据格式异常')
          }
        } else {
          console.error('API error:', res.msg)
          trainingRecords.value = []
          total.value = 0
          ElMessage.error(res.msg || '加载培训记录失败')
        }
      } catch (error) {
        console.error('加载培训记录失败:', error)
        trainingRecords.value = []
        total.value = 0
        ElMessage.error('加载培训记录失败')
      } finally {
        loading.value = false
      }
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.trainingId = ''
      searchForm.employeeId = ''
      loadTrainingRecords()
    }
    
    // 格式化出勤状态
    const formatAttendance = (status) => {
      const statusMap = {
        0: '未签到',
        1: '已签到',
        2: '迟到',
        3: '早退',
        4: '缺席'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取出勤状态标签类型
    const getAttendanceTagType = (status) => {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'warning',
        4: 'danger'
      }
      return typeMap[status] || 'info'
    }
    
    // 打开添加对话框
    const openAddDialog = () => {
      dialogType.value = 'add'
      form.id = null
      form.trainingId = ''
      form.employeeId = ''
      form.attendance = 0
      form.score = null
      form.feedback = ''
      dialogVisible.value = true
    }
    
    // 打开编辑对话框
    const openEditDialog = (row) => {
      dialogType.value = 'edit'
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
      dialogVisible.value = true
    }
    
    // 打开批量添加对话框
    const openBatchAddDialog = () => {
      batchForm.trainingId = ''
      batchForm.employeeIdsString = ''
      batchForm.attendance = 0
      batchDialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            let res
            const data = { ...form }
            
            if (dialogType.value === 'add') {
              res = await request.post('/api/training/records', data)
            } else {
              res = await request.put(`/api/training/records/${form.id}`, data)
            }
            
            if (res.code === 200) {
              ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
              dialogVisible.value = false
              loadTrainingRecords()
            } else {
              ElMessage.error(res.msg || (dialogType.value === 'add' ? '添加失败' : '修改失败'))
            }
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加失败:' : '修改失败:', error)
            ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
          }
        }
      })
    }
    
    // 提交批量添加表单
    const submitBatchForm = async () => {
      if (!batchFormRef.value) return
      
      try {
        const employeeIds = batchForm.employeeIdsString.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        
        if (employeeIds.length === 0) {
          ElMessage.warning('请输入有效的员工ID')
          return
        }
        
        const records = employeeIds.map(employeeId => ({
          trainingId: batchForm.trainingId,
          employeeId,
          attendance: batchForm.attendance
        }))
        
        const res = await request.post('/api/training/records/batch', records)
        
        if (res.code === 200) {
          ElMessage.success('批量添加成功')
          batchDialogVisible.value = false
          loadTrainingRecords()
        } else {
          ElMessage.error(res.msg || '批量添加失败')
        }
      } catch (error) {
        console.error('批量添加失败:', error)
        ElMessage.error('批量添加失败')
      }
    }
    
    // 删除培训记录
    const handleDelete = (id) => {
      ElMessageBox.confirm('确认删除该培训记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request.delete(`/api/training/records/${id}`)
          if (res.code === 200) {
            ElMessage.success('删除成功')
            loadTrainingRecords()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {})
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadTrainingRecords()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadTrainingRecords()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadTrainingRecords()
    })
    
    return {
      trainingRecords,
      loading,
      currentPage,
      pageSize,
      total,
      searchForm,
      formRef,
      form,
      batchFormRef,
      batchForm,
      dialogVisible,
      batchDialogVisible,
      dialogType,
      rules,
      loadTrainingRecords,
      resetSearch,
      formatAttendance,
      getAttendanceTagType,
      openAddDialog,
      openEditDialog,
      openBatchAddDialog,
      submitForm,
      submitBatchForm,
      handleDelete,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.training-records {
  padding: 0 24px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--app-text-color);
}

.page-subtitle {
  font-size: 16px;
  color: var(--app-secondary-text);
  max-width: 700px;
  margin: 0 auto 20px;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 12px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.search-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.07);
}

.search-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.custom-input {
  width: 200px;
  border-radius: 8px;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.data-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s;
  margin-bottom: 30px;
}

.data-card:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.08);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.grade-tag {
  font-weight: 500;
  border-radius: 10px;
  padding: 2px 8px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .action-bar {
    flex-wrap: wrap;
  }
  
  .action-btn {
    flex: 1;
    min-width: 0;
  }
}
</style> 